package com.sugon.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AuthCheck;
import com.sugon.annotation.LoginUser;
import com.sugon.consts.MoldReplacePartType;
import com.sugon.dao.ModuleReplacePartDao;
import com.sugon.entity.*;
import com.sugon.entity.dto.MoldReplacePartMatchParam;
import com.sugon.modules.base.model.vo.ProcessProgressConst;
import com.sugon.modules.mold.consts.MoldReplacePartProgress;
import com.sugon.modules.mold.consts.MoldSpStockState;
import com.sugon.modules.mold.model.vo.ModuleReplacePartParam;
import com.sugon.modules.mold.service.IMoldReplacePartManager;
import com.sugon.service.*;
import com.sugon.util.ApiBaseAction;
import com.sugon.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模具型芯备件接口
 *
 * @author YuXD
 * @since 2022-03-05
 */
@Api(tags = "模具换件记录API")
@RestController
@RequestMapping("/api/v1/moldReplacePart")
public class MoldReplacePartApiController extends ApiBaseAction {

    @Autowired
    private ModuleSpStockService moduleSpStockService;
    @Autowired
    private IMoldReplacePartManager moldReplacePartManager;
    @Resource
    private ModuleRepairRocordService moduleRepairRocordService;
    @Resource
    private ModuleArchivesService moduleArchivesService;
    @Resource
    private ModuleReplacePartDao moduleReplacePartDao;
    @Resource
    private ModuleMaintainPlanService moduleMaintainPlanService;
    @Resource
    private ModuleReplacePartService moduleReplacePartService;
    @Resource
    private ModuleSpDeptStockService moldSpDeptStockService;
    @Autowired
    private ModuleSpPurchasingBatchService moduleSpPurchasingBatchService;
    @Autowired
    private ModulPositionCorrelationService moldPosCorrelationService;

    /**
     * 模具换件记录查询API
     *
     * @param loginUser 当前登录用户
     * @param params    查询参数
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "模具换件记录查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moduleCode", value = "模具编码", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "typeMethod", value = "换件类型1维修换件 2定义维护换件", allowableValues = "1,2", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "replaceCode", value = "模具维修或维护工单编码", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @PostMapping
    public ApiResult<PageUtils> loadMoldReplacePart(@ApiIgnore @LoginUser SysUserEntity loginUser, @ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        return apiResult.success(moldReplacePartManager.queryList(params));
    }

    @AuthCheck
    @ApiOperation(value = "添加换件位置API")
    @PostMapping(value = "/addPosition")
    public ApiResult<String> addPosition(@ApiIgnore @LoginUser SysUserEntity loginUser, @RequestBody @Validated ModuleReplacePartParam moduleReplacePartParam, BindingResult bindingResult) {
        // 常规校验
        ApiResult<String> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        // 校验本次需要更换的模具位置列表 中是否有上一次未结束的
        List<String> moldPositionList = moduleReplacePartParam.getMoldPositionList();
        for (String moldPosition : moldPositionList) {
            if (moduleReplacePartDao.countUnPassedReplaceRecordNum(moldPosition) > 0) {
                return apiResult.failMsg("当前模具位置换件流程尚未结束，请耐心等待！");
            }
        }
        // 校验这个工单是否已换件结束  CQA-NE-00046_20220107 维护工单
        // MREP-20210428-0003 维修工单
        Integer typeMethod = moduleReplacePartParam.getTypeMethod();
        if (MoldReplacePartType.REPAIR.getValue().equals(typeMethod)) {
            // 模具维修工单
            ModuleRepairRocordEntity moldRepairRecord = moduleRepairRocordService.queryByCode(moduleReplacePartParam.getReplaceCode());
            Assert.notNull(moldRepairRecord);
            if (StrUtil.isEmpty(moldRepairRecord.getMoldId())) {
                return apiResult.failMsg("请先关联模具后再进行换件操作！");
            }
            if (MoldReplacePartProgress.PASSED.equals(moldRepairRecord.getProgress())) {
                return apiResult.failMsg("已审批通过，不允许继续添加换件记录！");
            }
        } else if (MoldReplacePartType.MAINTENANCE.getValue().equals(typeMethod)) {
            // 模具维护工单
            ModuleMaintainPlanEntity maintainPlanEntity = moduleMaintainPlanService.queryByCode(moduleReplacePartParam.getReplaceCode());
            Assert.notNull(maintainPlanEntity);
            if (MoldReplacePartProgress.PASSED.equals(maintainPlanEntity.getReplacePartProgress())) {
                return apiResult.failMsg("已审批通过，不允许继续添加换件记录！");
            }
        }
        ModuleArchivesEntity moduleArchives = moduleArchivesService.queryObject(moduleReplacePartParam.getMoldId());
        Assert.notNull(moduleArchives, "模具信息不存在，模具ID:{}", moduleReplacePartParam.getMoldId());
        // 设置模具使用次数
        moduleReplacePartParam.setUseTime(moduleArchives.getUseNo());
        moduleReplacePartParam.setDeptCode(moduleArchives.getSubShop());
        return moldReplacePartManager.addMoldReplacePartRecord(moduleReplacePartParam) ? apiResult.success() : apiResult.failMsg("添加失败，请稍后重试！");
    }

    @AuthCheck
    @ApiOperation(value = "删除模具换件位置API")
    @PostMapping(value = "/deletePosition")
    public ApiResult<String> addPosition(@ApiIgnore @LoginUser SysUserEntity loginUser, @RequestBody String[] ids) {
        ApiResult<String> apiResult = new ApiResult<>();
        for (String id : ids) {
            ModuleReplacePartEntity moduleReplacePart = moduleReplacePartDao.queryObject(id);
            if (moduleReplacePart == null) {
                continue;
            }
            Integer progress = moduleReplacePart.getProgress();
            if (ProcessProgressConst.PASSED.equals(progress)) {
                return apiResult.failMsg("已审核通过的换件记录不允许删除！");
            }
            // 删除模具换件记录
            moldReplacePartManager.deleteMoldReplacePartRecord(moduleReplacePart);
        }
        return apiResult.success();
    }

    @AuthCheck
    @ApiOperation(value = "找出匹配的模具换件位置API")
    @PostMapping("/findMatchedPosition")
    @ResponseBody
    public ApiResult<ModuleSpStockEntity> findMatchedPosition(@Validated @RequestBody MoldReplacePartMatchParam param, BindingResult bindingResult, @ApiIgnore @LoginUser SysUserEntity loginUser) {
        // 常规校验
        ApiResult<ModuleSpStockEntity> apiResult = getValidApiResult(bindingResult);
        if (apiResult != null) {
            return apiResult;
        }
        apiResult = new ApiResult<>();
        ModuleSpStockEntity moduleSpStock = moduleSpStockService.queryListByUniqueCode(param.getUniqueCode());
        if (moduleSpStock == null) {
            return apiResult.failMsg("未找到匹配的模具型芯，请确认！");
        } else {
            if (StrUtil.isNotEmpty(moduleSpStock.getUniqueBarCode())) {
                // 获取本次模具换件记录中支持的位置信息
                List<ModulPositionCorrelationEntity> moldPositionList = moduleReplacePartDao.queryModulePosition(param.getMethodType(), param.getReplaceCode());
                if (CollectionUtil.isNotEmpty(moldPositionList)) {
                    // 只返回已设置适用条码代码且匹配的位置信息
                    moduleSpStock.setPositionList(moldPositionList.stream().filter(moldPosition -> StrUtil.isNotEmpty(moldPosition.getBarCodeRange()) && ReUtil.isMatch(moldPosition.getBarCodeRange(), moduleSpStock.getUniqueBarCode())).collect(Collectors.toList()));
                }
            }
        }

        return apiResult.success(moduleSpStock);
    }

    @AuthCheck
    @ApiOperation(value = "模具换件记录关联型芯库存API")
    @RequestMapping("/associateMoldSpStock")
    @ResponseBody
    public ApiResult<String> associateMoldSpStock(@RequestParam("replacePartRecordId") String replacePartRecordId, @RequestParam("stockId") String stockId) {
        ApiResult<String> apiResult = new ApiResult<>();
        // 校验换件记录是否存在
        ModuleReplacePartEntity moduleReplacePart = moduleReplacePartService.queryObject(replacePartRecordId);
        if (moduleReplacePart == null) {
            return apiResult.failMsg("换件记录不存在，请确认！");
        }
        // 校验是否已关联
        if (StrUtil.isNotEmpty(moduleReplacePart.getStockId())) {
            return apiResult.failMsg("换件记录已关联型芯！");
        }
        // 校验型芯备件是否存在
        ModuleSpStockEntity moduleSpStock = moduleSpStockService.queryObject(stockId);
        if (moduleSpStock == null) {
            return apiResult.failMsg("型芯记录不存在，请确认！");
        }
        // 校验是否已使用
        if (MoldSpStockState.USED.equals(moduleSpStock.getState())) {
            return apiResult.failMsg("型芯备件已使用，请更换！");
        }
        // 校验下当前模具型芯是否适用于这个模具位置
        ModulPositionCorrelationEntity moldPosition = moldPosCorrelationService.queryObject(moduleReplacePart.getModulePositionId());
        Assert.notNull(moldPosition, "模具换件位置不存在！");
        String barCodeRange = moldPosition.getBarCodeRange();
        if (StrUtil.isEmpty(barCodeRange)) {
            return apiResult.failMsg("当前模具位置未配置适用型芯规则，暂不支持换件操作！");
        } else {
            List<String> barCodeList = StrUtil.split(barCodeRange, "|");
            if (!barCodeList.contains(moduleSpStock.getUniqueBarCode())) {
                return apiResult.failMsg("该备件不适用于当前模具位置，请确认！");
            }
        }
        moduleReplacePart.setStockId(stockId);
        if (moduleReplacePartService.update(moduleReplacePart) > 0) {
            // 更新库存状态和备件采购批次数
            moduleSpStock.setState(MoldSpStockState.USED);
            moduleSpStock.setStockOutDate(DateUtil.date());
            if (moduleSpStockService.update(moduleSpStock) > 0) {
                // 实时更新采购批次中的出库数
                moldSpDeptStockService.realtimeUpdateDeptStock(moduleSpStock.getWorkshop(), moduleSpStock.getMoldSpId());
                // 实时更新采购批次中的出库数
                moduleSpPurchasingBatchService.realtimePurchasingBacthStockState();
            }
        }
        return apiResult.success();
    }

}




